package com.cy.law.login.web;

import com.cy.law.db.entity.Human;
import com.cy.law.login.service.LoginService;
import com.cy.law.utils.SessionUtil;
import com.cy.law.utils.StringUtil;
import com.cy.law.vo.CodeMessage;
import com.cy.law.vo.RequestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Slf4j
public class LoginController {
    @Autowired
    LoginService loginService;

    @RequestMapping(value = "main/login/ajaxlogin", method = RequestMethod.POST)
    @ResponseBody
    public RequestResult ajaxLoginHandler(HttpServletRequest request, HttpServletResponse response, @RequestParam String un, @RequestParam String pw) throws Exception {
        RequestResult result = RequestResult.new0();
        //解密用户名密码
        String userName = StringUtil.base64Decode(un.trim());
        String password = pw.trim().isEmpty() ? "" : StringUtil.base64Decode(pw.trim());
        Human human = loginService.validateLogin(userName, password);
        if (human != null) {
            if (SessionUtil.login(request, human)) {
                result.setMapData("human", human);
                return result;
            } else {
                result.setMessage("Session写入失败,请联系管理员!");
                return result;
            }
        } else {
            return new RequestResult(CodeMessage.WRONG_USER_PSW);
        }
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public RequestResult logoutSystem(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            SessionUtil.logout(request);
            return RequestResult.new0();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return RequestResult.new1().setMessage("登出失败,请联系管理员!");
        }
    }
}
